package com.gyt.manager.common.base.exception;

import com.gyt.manager.common.base.response.Response;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

/**
 * @author gyt on 2021/4/27 14:53
 */
@ControllerAdvice
public class MyControllerAdvice {



    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(value = Exception.class)
    public Response errorHandler(Exception ex){

        int statusCode;
        StringBuilder msg = new StringBuilder();
        if (ex instanceof HttpRequestMethodNotSupportedException) {
            statusCode = 405;
            msg = new StringBuilder("不支持当前请求方法！请使用 " + Arrays.toString(((HttpRequestMethodNotSupportedException) ex).getSupportedMethods()) + " 方式请求");
        } else if (ex instanceof MissingServletRequestParameterException) {
            statusCode = 400;
            msg = new StringBuilder("缺少请求参数！ [" + ((MissingServletRequestParameterException) ex).getParameterType() + "]" + ((MissingServletRequestParameterException) ex).getParameterName());
        } else if (ex instanceof MethodArgumentNotValidException) {
            statusCode = 400;
            BindingResult bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError error : allErrors) {
                msg.append(error.getDefaultMessage()).append("\n");
            }
        } else if (ex instanceof RuntimeException) {
            statusCode = 500;
            msg = new StringBuilder(ex.getMessage());
        } else {
            statusCode = 500;
            msg = new StringBuilder("未知错误！" + ex.getMessage() + "!!!");
        }
        Response response = new Response();
        response.setCode(String.valueOf(statusCode));
        response.setMsg(msg.toString());
        return response;
    }
}
